package com.lwq.nacos.grayscale.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.lwq.nacos.grayscale.constants.Constants;
import com.lwq.nacos.grayscale.gray.NacosMetaDataContext;
import com.lwq.nacos.grayscale.gray.NacosMetaDataContextHolder;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 基于servlet的过滤器，对web支持
 */
@Slf4j
public class ServletHeaderFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try{
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            //从header中取灰度标识
            String grayName = request.getHeader(Constants.GRAY_HEADER_NAME);
            if (StrUtil.isNotBlank(grayName)){
                NacosMetaDataContextHolder.getContext().put(Constants.GRAY_HEADER_NAME, grayName);
            }
            filterChain.doFilter(servletRequest, servletResponse);
        }catch (Exception e){
            log.error("GrayHeaderNameFilter doFilter error",e);
        }finally {
            NacosMetaDataContextHolder.remove();
        }
    }

    @Override
    public void destroy() {
        NacosMetaDataContextHolder.remove();
    }
}
